import union from '@turf/union'

export function coordId (coord) {
  return coord[0].toString() + ',' + coord[1].toString()
}

export function mergeLineStrings (a, b) {
  const s1 = coordId(a.coordinates[0])
  const e1 = coordId(a.coordinates[a.coordinates.length - 1])
  const s2 = coordId(b.coordinates[0])
  const e2 = coordId(b.coordinates[b.coordinates.length - 1])
  let coords
  if (s1 === e2) {
    coords = b.coordinates.concat(a.coordinates.slice(1))
  } else if (s2 === e1) {
    coords = a.coordinates.concat(b.coordinates.slice(1))
  } else if (s1 === s2) {
    coords = a.coordinates.slice(1).reverse().concat(b.coordinates)
  } else if (e1 === e2) {
    coords = a.coordinates.concat(b.coordinates.reverse().slice(1))
  } else {
    return null
  }
  return {
    type: 'LineString',
    coordinates: coords
  }
}

export function mergeLines (jsonFeatures) {
  const res = mergeJsonFeatures(jsonFeatures)
  const geoms = res.geometry.coordinates.map(coords => {
    return {
      type: 'LineString',
      coordinates: coords
    }
  })
  let lineStrings = geoms.slice()
  let result = []
  while (lineStrings.length > 0) {
    let ls = lineStrings.shift()
    lineStrings = lineStrings.reduce(function (accum, cur) {
      const merged = mergeLineStrings(ls, cur)
      if (merged) {
        // Accumulate the merged LineString
        ls = merged
      } else {
        // Put the unmerged LineString back into the list
        accum.push(cur)
      }
      return accum
    }, [])
    result.push(ls)
  }
  if (result.length === 1) {
    result = result[0]
  } else {
    result = {
      type: 'MultiLineString',
      coordinates: result.map(function (ls) { return ls.coordinates })
    }
  }
  jsonFeatures[0].geometry = result
  return jsonFeatures[0]
}

export function mergeJsonFeatures (features) {
  let res = null
  for (let i = 1; i < features.length; i++) {
    const f = i === 1 ? features[0] : res
    res = union(f, features[i])
  }
  return res
}
